import React from "react";
import { connectToUser } from "./connecters/connectTouser-6.js";
import { connect, createStore, Provider } from './redux-10.jsx';

// reduce 用于规范 state 创建流程的函数
const reducer = (state, {type, payload = {}}) => {
    if (type === 'updateUser') {
        return {
            ...state,
            user: {
                ...state.user,
                ...payload
            }
        }
    } else {
        return state;
    }
}
const initState = {
    user: {
        name: 'tom',
        age: 99
    },
    group: {
        name: '航海网'
    }
};
const store = createStore(reducer, initState);

const User = connectToUser(({user}) => {
    console.log('User 组件')
    return (
        <div>
            User: {user.name}
        </div>
    );
})

const UserModifier = connectToUser(({updateUser, dispatch, user, children}) => {
    console.log('UserModifier 组件')
    const changeHandler = (e) => {
        updateUser({
            name: e.target.value
        });
    }
    return (
        <div>
            {children}
            <input type="text" value={user.name} onChange={changeHandler}/>
        </div>
    );
});

const A = () => {
    console.log('A 组件')
    return <section>A 组件<User/></section>;
}
const B = () => {
    console.log('B 组件')
    return <section>B 组件<UserModifier num={1}>DDD</UserModifier></section>;
}
const C = connect(state => {
    return {
        group: state.group
    }
})(({group, dispatch}) => {
    console.log('C 组件');

    const userHandlerPromise = () => {
        dispatch({type: 'updateUser', payload: fetchUserPromise().then(v => v)})
    }
    const userHandler = () => {
        dispatch(fetchUser);
    }
    return (<div>
            <section>C 组件 = <p>Group: {group.name}</p></section>
            <button onClick={userHandlerPromise}>异步获取数据-payload是promise</button>
            <button onClick={userHandler}>异步获取数据-payload是object</button>
        </div>);
})

function fetchUserPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            Math.random() > 0.5 ? resolve({name: Math.random()}) : reject({name: '请求失败'})
        }, 2000)
    })
}
function fetchUser (dispatch) {
    // ,模拟异步请求数据
    setTimeout(() => {
        dispatch({type: 'updateUser', payload: {name: Math.random()}});
    }, 2000)
}
function App() {
    return (
        <Provider store={store}>
            <A/>
            <B/>
            <C/>
        </Provider>
    );
}

export default App;